package com.hb.encryptor;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author hubin
 * @description
 * @createTime 2024/3/8 14:43
 */
@Component
@Primary
public class AesEncryptor implements IEncryptor {

    @Override
    public String encrypt(Object plain, String key) {
        byte[] bytes = key.getBytes();
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, bytes);
        String encryptContent = aes.encryptBase64(plain.toString());
        return "pier_rois_" + encryptContent;
    }

    @Override
    public String decrypt(Object cipher, String key) {
        if (cipher == null || !StringUtils.hasLength(cipher.toString())) {
            return "";
        }
        String cipherPrefix = cipher.toString().substring(0, 10);
        if (!cipherPrefix.equals("pier_rois_")) {
            return cipher.toString();
        }
        byte[] bytes = key.getBytes();
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, bytes);
        String cipherContent = cipher.toString().substring(10);
        return aes.decryptStr(cipherContent, CharsetUtil.CHARSET_UTF_8);
    }
}
